
import { toByteArray as b64_to_u8arr, fromByteArray as u8arr_to_b64 } from 'base64-js'
export {
  b64_to_u8arr,
  u8arr_to_b64
}
/**
 * 生成随机指定位数随机字符串,如果环境允许加解密工具,
 * 那么就是用环境的加解密工具随机生成指定位数的数组,
 * 如果环境不支持,就使用Math.random 随机生成指定位数的类型数组
 * 内部使用8位有符号无符号整型类型数组作为随机key的储存,
 * @param  bits_length 要生成的总位数,非数组长度
 * @returns 
 */
export function getRandomNumberArr(bits_length = 128): Uint8Array {
  if (bits_length < 1) return new Uint8Array(0);
  let computedLength = Math.ceil(bits_length / 8);
  let tempArr = new Uint8Array(computedLength);
  let canGetRandom = window.crypto?.getRandomValues;
  if (canGetRandom) {
    // 如果环境自带生成工具,调用原生的
    return window.crypto.getRandomValues(tempArr);
  }

  // 否则使用Math.Random随机生成
  for (let index = 0; index < computedLength; index++) {
    tempArr[index] = Math.floor(Math.random() * 256);
  }
  return tempArr;
}

export const encoder = new TextEncoder()
export const decoder = new TextDecoder()

export function str_to_u8arr(str: string) {
  return encoder.encode(str)
}

export async function GenerateRSAKeys(): Promise<CryptoKeyPair> {
  return window.crypto.subtle.generateKey(
    {
      name: 'RSA-OAEP',
      modulusLength: 1024,
      publicExponent: new Uint8Array([1, 0, 1]),
      hash: "SHA-256",
    },
    true,
    ['decrypt', 'encrypt']
  )
}


/**
 * 
 * @param boo 表示是否生成头或尾部 (未完善)
 * @returns 
 */
export async function GenerateRSAKeys_to_B64(boo?: boolean) {

  const v = await GenerateRSAKeys()


  const prik_b64 = await window.crypto.subtle.exportKey(
    "pkcs8",
    v.privateKey
  ).then((ab) => {
    const u8arr = new Uint8Array(ab)
    return u8arr_to_b64(u8arr)
  })
  const pubk_b64 = await window.crypto.subtle.exportKey(
    "spki",
    v.publicKey
  ).then((ab) => {
    const u8arr = new Uint8Array(ab)
    return u8arr_to_b64(u8arr)
  })
  return { prik_b64, pubk_b64 }
}